package com.nanosn.coffeemaker;

import java.util.Enumeration;
import java.util.logging.ConsoleHandler;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import uk.co.flamingpenguin.jewel.cli.Cli;
import uk.co.flamingpenguin.jewel.cli.CliFactory;

/**
 * The main entry point of the application.
 * @author selkhateeb
 */
public class Main
{

    /**
     * Main function in the application
     * @param args the command line arguments
     */
    public static void main(String[] args)
    {
        Application.logger.fine("Application Started...");
        try
        {
            ParseArguments(args);
        }
        catch (Exception ex)
        {
            Application.logger.log(Level.SEVERE, ex.getMessage(), ex);
        }

        Application.logger.fine("Application Ended...");

    }

    /**
     * Parses the command line arguments and run application options
     * Pre: User passed command line argument
     * Post: Application started with specified options
     * @param args
     * @throws java.lang.Exception
     */
    private static void ParseArguments(final String[] args) throws Exception
    {
        final ICommandLineArguments cla =
                CliFactory.parseArguments(ICommandLineArguments.class, args);


        //Set the logger if user passed debug or verbose
        if (cla.isDebug())
        {
            PrepareLogger(Level.ALL);
        }
        else if (cla.isVerbose())
        {
            PrepareLogger(Level.FINE);
        }
        else
        {
            PrepareLogger(Level.INFO);
        }


        //Run the applicaiton based on the user selection
        if (cla.isStartProject())
        {
            // <editor-fold defaultstate="collapsed" desc="Logging">
            if (Application.logger.isLoggable(Level.FINE))
            {
                Application.logger.fine("User is creating new project named: " + cla.getStartProject());
            }
            // </editor-fold>
            //User is creating new project
            Application.StartProject(cla.getStartProject());
        }
        else if (cla.isStartApplication())
        {
            Application.StartApplicaiton(cla.getStartApplication());
        }
        else if (cla.isVersion())
        {
            System.out.println(Application.getVersion());
        }
        else if (cla.isSql())
        {
            Application.PrintSqlSchema(cla.getSql());
        }
        else
        {
            final Cli<ICommandLineArguments> cli = CliFactory.createCli(ICommandLineArguments.class);
            System.out.println(cli.getHelpMessage());
        }
    }

    /**
     * Prepares the logger to log all messages to console.
     * Pre:
     * Post: The logger set to log to console
     * @throws java.lang.SecurityException
     */
    private static void PrepareLogger(final Level logLevel) throws SecurityException
    {

        final ConsoleHandler handler = new ConsoleHandler();
        handler.setLevel(logLevel);
        handler.setFormatter(new LogFormatter());
        Application.logger.setUseParentHandlers(false);
        Application.logger.addHandler(handler);
        final LogManager lm = LogManager.getLogManager();
        final Enumeration<String> e = lm.getLoggerNames();
        while (e.hasMoreElements())
        {
            String w = e.nextElement();
            Logger l = lm.getLogger(w);
            l.setLevel(logLevel);
        }
    }
}
